require 'rexml/document'  # ruby stdlib
require 'uri'             # ruby stdlib

module SitemapSpider
  class SitemapRecord
    attr_accessor :lastmod, :changefreq, :priority
    attr_reader :loc, :url, :images

    def initialize(obj)
      if obj.kind_of?(Hash)
        @loc = obj[:loc]
        @lastmod = obj[:lastmod]
        @changefreq = obj[:changefreq]
        @priority = obj[:priority]
        @images = []
        if obj[:images]
          obj[:images].each do |image|
            @images << ImageRecord.new(image)
          end
        end
      else
        @loc = obj.respond_to?(:loc) ? obj.loc : obj.to_s
        @lastmod = obj.respond_to?(:lastmod) ? obj.lastmod : nil
        @changefreq = obj.respond_to?(:changefreq) ? obj.changefreq : nil
        @priority = obj.respond_to?(:priority) ? obj.priority : nil
        @images = obj.respond_to?(:images) ? obj.images : []
      end
      if obj.kind_of?(URI::Generic)
        @url = obj.dup
      else
        @url = URI.parse(@loc)
      end
    end

    def attributes
      ([:loc, :lastmod, :changefreq, :priority].collect {|a| a if self.send(a)}).compact
    end

    def attribute_to_element(attr)
      e = REXML::Element.new(attr.to_s)
      e.text = self.send(attr)
      return e
    end

    def to_url_element
      url_e = REXML::Element.new('url')
      attributes.each {|a| url_e.add_element(attribute_to_element(a))}
      @images.each {|i| url_e.add_element(i.to_image_element)}
      return url_e
    end

    def url=(urlobj)
      @loc = urlobj.to_s
      @url = urlobj
    end

    def loc=(locobj)
      @loc = locobj
      @url = URI.parse(locobj)
    end

    # Note: only the "location" address is significant
    def ==(oth)
      oth.respond_to?(:loc) and (@loc == oth.loc)
    end
  end
end
